package com.gjh.realm;
import com.gjh.domain.system.Module;
import com.gjh.domain.system.User;
import com.gjh.service.system.ModuleService;
import com.gjh.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SaasRealm extends AuthorizingRealm{
    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //        判断email和password‘
//        先根据email查询用户
//        根据用户的password和页面上输入的password比较
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String email = token.getUsername();
        char[] password = token.getPassword();
        String password_page = new String(password);
        User user = userService.findByEmail(email);
        if(user!=null){
            String password_db = user.getPassword();
            if(password_db.equals(password_page)){
                return new SimpleAuthenticationInfo(user,password_db,getName());
            }
        }
        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<Module> moduleList = moduleService.findModuleListByUser(user);
        for (Module module : moduleList) {
            info.addStringPermission(module.getName());//相当于告诉框架   登录人有这个权限
        }
        return info;
    }


}
